package com.monolith.jd.demo.common.util;


import com.monolith.jd.demo.common.util.http.SSLClients;
import org.apache.http.Header;
import org.apache.http.HttpStatus;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.message.BasicHeader;
import org.apache.http.util.EntityUtils;

import java.io.IOException;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @author 郭文梁
 * <p>${DATE} ${TIME} Create by 郭文梁</p>
 * <p>FOR: </p>
 */

public class HttpUtil {
    private static CloseableHttpClient client = SSLClients.createHttpsClient();


    public static String get(String urlStr) throws IOException {
        HttpGet get = new HttpGet(urlStr);

        CloseableHttpResponse response = client.execute(get);
        if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
            return EntityUtils.toString(response.getEntity());
        } else {
            return null;
        }
    }

    public static byte[] downloadAsByteArray(String url) throws IOException {
        HttpGet get = new HttpGet(url);
        CloseableHttpResponse response = client.execute(get);
        if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
            return EntityUtils.toByteArray(response.getEntity());
        } else {
            return null;
        }
    }


    public static String postWithStringBody(String url, String body) throws IOException {
        HttpPost post = new HttpPost(url);
        post.setEntity(new StringEntity(body));
        CloseableHttpResponse response = client.execute(post);
        if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
            return EntityUtils.toString(response.getEntity());
        }
        return null;
    }

    public static String postWithStringBody(String url, String postBody, Map<String, String> headers) throws IOException {
        HttpPost post = new HttpPost(url);
        List<Header> headerList = headers.entrySet().stream().map(e -> new BasicHeader(e.getKey(), e.getValue())).collect(Collectors.toList());
        post.setHeaders(CollectionUtil.toArray(headerList, new Header[headerList.size()]));
        post.setEntity(new StringEntity(postBody));

        try (CloseableHttpResponse response = client.execute(post)) {
            if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
                return EntityUtils.toString(response.getEntity());
            }
            return null;
        }
    }


}
